<?php

namespace addons\third\library;

use EasyWeChat\MiniProgram\Encryption\Encryptor;
use think\Config;
use think\Exception;
use think\Log;
use fast\Http;

/**
 * 微信小程序
 */
class Wemini
{

    const GET_AUTH_CODE_URL = '';
    const GET_OPENID_URL = 'https://api.weixin.qq.com/sns/jscode2session';

    /**
     * 配置信息
     * @var array
     */
    private $config = [];

    public function __construct($options = [])
    {
        if ($config = Config::get('third.wemini')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }
    public function getOpenId($code)
    {
        if (!isset($code) && !$code) {
            throw new Exception('Code为空或请求异常', 2);
        }
        $data = [];
        $data['appid'] = $this->config['app_id'];
        $data['secret'] = $this->config['app_secret'];
        $data['js_code'] = $code;
        $data['grant_type'] = 'authorization_code';
        $url = self::GET_OPENID_URL . '?' . http_build_query($data);
        $ret = Http::get($url);
        $result = json_decode($ret, true);
        if (!$result || isset($result['errcode'])) {
            Log::record($ret, Log::ERROR);
            throw new Exception($result['errmsg'], 3);
        }
        return $result;
    }

    /**
     * 获取用户信息
     * @param array $params
     * @return array
     */
    public function getUserInfo($params = [])
    {
        $params = $params ? $params : $_GET;
        list($code, $rawData, $signature, $encryptedData, $iv) = array_values($params);

        if (empty($code) || empty($rawData) || empty($signature) || empty($encryptedData) || empty($iv)) {
            return [];
        }
        $result = $this->getOpenId($params['code']);

        $this->openid = $result['openid'];

        // 数字签名校验 
        $signature2 = sha1(htmlspecialchars_decode($rawData . $result['session_key']));
        if ($signature != $signature2) {
            return [];
        }
        // 获取信息，对接口进行解密  
        $Encryptor = new Encryptor($this->config['app_id'], '', '');
        $retult = $Encryptor->decryptData($result['session_key'], $iv, $encryptedData);
        if (isset($retult['gender'])) {
            if ($retult['gender'] == 2) {
                $retult['sex'] = 0;
            } else if ($retult['gender'] == 0) {
                $retult['sex'] = 2;
            } else {
                $retult['sex'] = 1;
            }
        } else {
            $retult['sex'] = 1;
        }
        $data['userinfo'] = [
            'openid'    => $retult['openId'],
            'language'  => $retult['language'],
            'nickname'  => $retult['nickName'],
            'avatar'    => $retult['avatarUrl'],
            'sex'       => $retult['sex'],
            'city'      => $retult['city'],
            'province'  => $retult['province'],
            'country'   => $retult['country'],
        ];
        return $data;
    }
    /**
     * 解密手机号
     *
     * @param array $params
     * @return void
     */
    public function decryptorMobile($params = [])
    {
        $params = $params ? $params : $_GET;
        list($code, $encryptedData, $iv) = array_values($params);
        if (empty($code) || empty($encryptedData) || empty($iv)) {
            return [];
        }
        $result = $this->getOpenId($params['code']);
        $this->openid = $result['openid'];
        $session_key = $result['session_key'];
        // 获取信息，对接口进行解密
        $Encryptor = new Encryptor($this->config['app_id'], '', '');
        $data = $Encryptor->decryptData($session_key, $iv, $encryptedData);
        return ['countryCode' => $data['countryCode'], 'purePhoneNumber' => $data['purePhoneNumber'], 'openid' => $result['openid']];
    }
}
